package service

import (
    "context"
    "gitee.com/WisdomClassroom/CollegeStruct/glb"
    "gitee.com/WisdomClassroom/core"
    "gitee.com/WisdomClassroom/core/models"
    "gitee.com/WisdomClassroom/core/protobufs/v1/pb"
    "github.com/jinzhu/gorm"
    "time"
)

func (s *Service) DeleteCollege(_ context.Context, in *pb.DeleteCollegeRequest) (*pb.DeleteCollegeResponse, error) {
    token := core.NewToken()
    err := token.UnpackToken(in.AuthToken, &core.FlagTokenCert)
    if err != nil {
        return &pb.DeleteCollegeResponse{Status: &pb.ResponseStatus{
            Code: pb.ResponseStatusCode_NotAuth, Error: err.Error(),
        },}, nil
    }

    if token.Type != core.UserRoleTypeCodeRoot {
        return &pb.DeleteCollegeResponse{Status: &pb.ResponseStatus{Code: pb.ResponseStatusCode_OtherError,
            Message: "用户没有权限",
        },}, nil
    }
    userOfReq := models.UserModel{
        Model: models.Model{
            UUID: token.UUID,
        },
        Type: core.UserRoleTypeCodeRoot,
    }
    err = glb.DB.Scopes(notDeleted).Where(&userOfReq).First(&userOfReq).Error
    if err == gorm.ErrRecordNotFound {
        return &pb.DeleteCollegeResponse{Status: &pb.ResponseStatus{Code: pb.ResponseStatusCode_OtherError,
            Message: "用户没有权限或编号不存在",
        },}, nil
    } else if err != nil {
        glb.Logger.Error(err.Error())
        return deleteCollegeRespSvrErr, nil
    }

    if len(in.WillDeleteUUID) != 36 {
        return &pb.DeleteCollegeResponse{Status: &pb.ResponseStatus{Code: pb.ResponseStatusCode_OtherError,
            Message: "学院编号不正确",
        },}, nil
    }

    collegeWithUUID := models.CollegeModel{
        Model: models.Model{
            UUID: in.WillDeleteUUID,
        },
    }
    err = glb.DB.Scopes(notDeleted).Where(&collegeWithUUID).First(&collegeWithUUID).Error
    if err == gorm.ErrRecordNotFound {
        return &pb.DeleteCollegeResponse{Status: &pb.ResponseStatus{Code: pb.ResponseStatusCode_OtherError,
            Message: "学院编号不存在",
        },}, nil
    } else if err != nil {
        glb.Logger.Error(err.Error())
        return deleteCollegeRespSvrErr, nil
    }

    college := models.CollegeModel{
        Model: models.Model{
            Deleted:    true,
            DeleteTime: time.Now().Unix(),
        },
    }
    err = glb.DB.Scopes(notDeleted).Where("uuid=?", in.WillDeleteUUID).Model(&college).Updates(college).Error
    if err != nil {
        glb.Logger.Error(err.Error())
        return deleteCollegeRespSvrErr, nil
    }

    return &pb.DeleteCollegeResponse{
        Status: &pb.ResponseStatus{Code: pb.ResponseStatusCode_Suc},
    }, nil
}
